package com.icode.sigle;


/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-14 17:04
 */
public class LazyLoad {

    private static volatile LazyLoad instance;

    private LazyLoad() {
    }
    public static LazyLoad getInstance(){
        if (instance==null){    //判是否已经创建对象，避免多次去获取执行同步代码块
            synchronized (LazyLoad.class){  //同步加锁，防止多个线程同时创建
                //判是否已经创建对象
                //在排队的线程进入该代码块，如果不做判断，当前线程即使创造了实例，下一个线程也不知道，就会继续创建一个实例
                if (instance==null){
                    instance = new LazyLoad();
                }
            }
        }
        return instance;
    }

}

class Test02{
    public static void main(String[] args) {
        for (int i = 20; i > 0; i--) {
            new Thread(()->{
                System.out.println(LazyLoad.getInstance());
            }).start();
        }
    }
}
